package org.javahispano.javacup.tacticas.tacticas_aceptadas.masia;

import java.util.List;

import org.javahispano.javacup.modelo.Comando;
import org.javahispano.javacup.modelo.ComandoIrA;
import org.javahispano.javacup.modelo.Constantes;
import org.javahispano.javacup.modelo.Posicion;
import org.javahispano.javacup.modelo.SituacionPartido;

public class Defense {
	private SituacionPartido sp;
	private List<Comando> comandos;
	private final Data data;
	private final int goalkeeper = 0;
	private int countDefense = 5;
	
	public void setCountDefense(int countDefense) {
		this.countDefense = countDefense;
	}

	public Defense(List<Comando> comandos, Data data) {
		super();		
		this.comandos = comandos;
		this.data = data;
	}
	
	public void execute(SituacionPartido sp, boolean attacking){
		this.sp = sp;
		int[] opponents = Constantes.centroArcoInf.indicesMasCercanos(sp.rivales());
		Posicion[] players = sp.misJugadores();
		boolean[] pressing = new boolean[11];
		int playerToBall = getBall(attacking);
		pressing[playerToBall] = true;
		for(int opponent: opponents){
			int[] closest = sp.rivales()[opponent].indicesMasCercanos(sp.misJugadores());
			for(int player: closest){
	    		if((isDefender(player, playerToBall))&& !pressing[player]){
	    			players[player] = press(opponent, attacking);
	    			comandos.add(new ComandoIrA(player, players[player]));
	    			pressing[player] = true;
	    			break;
	    		}
	    	}
		}		
	}

	private int getBall(boolean attacking) {
		if(data.getIterToBall() >= 0)
			comandos.add(new ComandoIrA(data.getPlayerClosetBall(), data.getPosBall(data.getIterToBall())));
		if(!attacking){
			int opponentIterToBall = data.getOpponentIterToBall();
			if(opponentIterToBall >= 0) {
				Posicion pos = data.getPosBall(opponentIterToBall).moverAngulo(data.getPosBall(opponentIterToBall).angulo(Constantes.centroArcoInf),Constantes.DISTANCIA_CONTROL_BALON);
				comandos.add(new ComandoIrA(pos.indiceMasCercano(sp.misJugadores(), goalkeeper), pos));
				return pos.indiceMasCercano(sp.misJugadores(), goalkeeper);
			}			
		}
		return data.getPlayerClosetBall();
	}

	private Posicion press(int opponent, boolean attacking){
		if(attacking)
			return  sp.rivales()[opponent].moverAngulo(sp.rivales()[opponent].angulo(sp.balon()), Constantes.DISTANCIA_CONTROL_BALON - Constantes.VELOCIDAD_MAX);
		return  sp.rivales()[opponent].moverAngulo(sp.rivales()[opponent].angulo(Constantes.centroArcoInf),Constantes.DISTANCIA_CONTROL_BALON - Constantes.VELOCIDAD_MAX);
	}

	private boolean isDefender(int player, int playerToBall) {
		int countDefense = this.countDefense + (playerToBall< this.countDefense? 1 : 0);
		return player != goalkeeper && (player < countDefense);
	}
}
